const app = getApp();
var that;
var util = require('../../utils/util.js');
var today = util.formatDay(new Date());
var day;
var UserArray = [];

Page({
  data: {
    img1: '/pages/img/image_sending.png',
    img2: '/pages/img/image_complete.png',
    hidden: '',
    date: util.formatDay(new Date()),
    id: "",
    code: "",
    stall: "",
    trackState: "",
    time: "08:00",
    carName: "",
    driverName: "",
    driverId: "",
    Users: [],
    UserIndex: 0,
    sea_name: "", // 客户名称搜索条件
    sea_code: "", // 客单号搜索条件
    file: "", // 图片文件路径

    array: [], // 初始数据数组
    current_page: 1, // 当前页码
    pageSize: 3, // 每页显示的数据条数
    hasMore: true, // 是否还有更多数据
    showGoTop: false, // 控制回到顶部按钮是否显示
    scrollToView: '',  // 用于指定要滚动到的元素ID
  },

  /**
   * 监听输入的客户名称
   */
  nameInp: function (e) {
    this.setData({
      sea_name: e.detail.value
    });
  },

  /**
   * 监听输入的客户单号
   */
  codeInp: function (e) {
    this.setData({
      sea_code: e.detail.value
    });
  },

  /**
   * 页面加载时执行的操作
   */
  onLoad: function (options) {
    that = this;
    day = options.day;
    if (day != null) {
      today = day;
    } else if (getApp().day != null) {
      today = getApp().day;
    }
    this.search(); // 初始化加载订单数据
    var title = "业务";
    wx.setNavigationBarTitle({
      title: title
    });
  },
  onShow: function (options) {
    this.getTabBar().setData({
      current: 'orders'
    })
  },

  /**
   * 用户选择司机时触发
   */
  bindUserChange: function (e) {
    this.setData({
      UserIndex: e.detail.value,
      driverName: UserArray[e.detail.value].name,
      driverId: UserArray[e.detail.value].id,
      carName: UserArray[e.detail.value].carName,
    })
  },

  /**
   * 滚动到底部时触发
   */
  loadMore: function () {
    console.log('loadMore method is called'); // 调试信息
    if (!this.data.hasMore) {
      console.log('No more data to load'); // 调试信息
      return;
    }

    this.setData({
      current_page: this.data.current_page + 1
    }, () => {
      this.search();
    });
  },
  // 监听 <scroll-view> 的滚动事件
  onScrollViewScroll(event) {
    const scrollTop = event.detail.scrollTop;
    this.setData({
      showGoTop: scrollTop > 200
    });
  },

  // 点击回到顶部按钮时触发
  goTop() {
    console.log("gotop")
    this.setData({
      scrollToView: 'top' // 设置为需要滚动到的元素ID
    }, () => {
      // setData 是异步的，这里可以确保在数据更新后执行一些逻辑
      console.log('Set scrollToView to top');
    });
  },
  /**
   * 获取订单数据
   */
  search: function () {
    const that = this;
    if (!isLogin()) {
      wx.showToast({
        title: "请先登录系统才能查看自己的订单!",
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!isUserType()) {
      wx.showToast({
        title: "请先录入您的身份信息,进入我的页面点击点击个人资料录入姓名身份后才可接单!",
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 构建查询字符串
    var otherSearchStr = "";
    if (that.data.sea_name != "") {
      otherSearchStr += "&customerName=" + encodeURIComponent(that.data.sea_name);
    }
    if (that.data.sea_code != "") {
      otherSearchStr += "&orderCode=" + encodeURIComponent(that.data.sea_code);
    }

    otherSearchStr += '&beginOrderTime=' + today + " 00:00:00";
    otherSearchStr += "&pageCurrent=" + that.data.current_page + "&pageSize=" + that.data.pageSize;

    console.log(app.serverIP + '/kkl/cms/app/OrdersCarrier/page?token=' + app.token + otherSearchStr);
    wx.request({
      url: app.serverIP + '/kkl/cms/app/OrdersCarrier/page?token=' + app.token + otherSearchStr,
      dataType: "json",
      success: function (res) {
        if (res.data.code == "200") {
          const newData = res.data.data.datalist.map(item => {
            return {
              ...item,
              orderTime: item.orderTime.substring(5, 16),
              upTime: item.upTime ? item.upTime.substring(5, 16) : '',
              downTime: item.downTime ? item.downTime.substring(5, 16) : ''
            };
          });

          // 去重处理
          const updatedArray = [...new Set([...that.data.array.map(a => a.orderCode), ...newData.map(n => n.orderCode)])];
          const finalArray = that.data.array.filter(existingItem => updatedArray.includes(existingItem.orderCode)).concat(newData);

          that.setData({
            array: finalArray,
            hasMore: newData.length === that.data.pageSize // 如果返回的数据少于每页大小，说明已无更多数据
          });
        } else {
          wx.showToast({
            title: "获取订单失败，请稍后再试！",
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function (err) {
        console.error('Failed to fetch orders:', err);
        wx.showToast({
          title: "网络请求失败，请检查网络连接！",
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  /**
   * 关闭提货图片弹窗
   */
  closeDialog: function () {
    this.setData({
      istrue: false
    })
  },

  /**
   * 打开提货图片弹窗
   */
  openDialog: function (e) {
    console.log(e.target.id)
    this.setData({
      istrue: true,
      fromId: e.target.id
    })
  },

  /**
   * 点击按钮导航到订单详情页面
   */
  btnclick: function (e) {
    wx.navigateTo({
      url: "/pages/orders_detail/orders_detail?id=" + e.target.id
    });
  },

  /**
   * 保存并关闭弹窗
   */
  saveDialog: function (e) {
    console.log(e.target.id);
    var obj = {
      "id": "",
      "companyId": getApp().userInfo.companyId,
      "fromId": that.data.fromId,
      "path": that.data.file,
      "thumbnail": that.data.file,
    };
    wx.request({
      url: app.serverIP + '/kkl/cms/app/fileInfo/add?token=' + app.token,
      method: "POST",
      data: JSON.stringify(obj),
      contentType: "application/json",
      success: function (res) {
        if (res.data.code == "200") {
          wx.showToast({
            title: "操作成功\n",
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: "修改失败:" + res.data.code,
            icon: 'none',
            duration: 2000
          })
          console.log(res.data.message)
        }
      },
    })
    this.setData({
      istrue: false
    })
  },

  /**
   * 选择图片
   */
  chooseImage: function (e) {
    wx.chooseMedia({
      sizeType: ['original', 'compressed'], // 图片自动压缩
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      mediaType: ['image'],
      count: 1,
      success: function (res) {
        // 上传前对图片进行压缩
        wx.compressImage({
          src: res.tempFiles[0].tempFilePath, // 图片路径
          quality: 50, // 压缩质量
          success: function (res) {
            console.log(res.tempFilePath)
            wx.uploadFile({
              url: app.imgIP + "/kkl/upload/fileUpload?folderName=img", // 请求地址
              data: "",
              filePath: res.tempFilePath,
              name: "file",
              header: {
                "Content-Type": "multipart/form-data"
              },
              formData: {
                "user": "test",
              },
              success: function (res) {
                var imgdata = JSON.parse(res.data);
                that.setData({
                  files: app.imgIP + imgdata.data.image,
                  file: imgdata.data.image
                })
              }
            })
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }
    })
  },

  /**
   * 预览图片
   */
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: [this.data.files] // 需要预览的图片http链接列表
    })
  },

  /**
   * 检测下拉刷新事件
   */
  onPullDownRefresh: function () {
    if (day != null) {
      today = day;
    } else if (getApp().day != null) {
      today = getApp().day;
    }
    this.setData({
      current_page: 1, // 重置当前页码
      array: [], // 清空数组
    }, () => {
      this.search();
    });
    wx.stopPullDownRefresh();
  },

  /**
   * 根据搜索条件重新加载数据
   */
  searchQuery: function () {
    this.setData({
      current_page: 1, // 重置当前页码
      array: [], // 清空数组
    }, () => {
      this.search();
    });
  }
})

/**
 * 检查用户是否登录
 */
function isLogin() {
  if (app.userInfo != null) {
    return true;
  } else {
    console.log("用户还没有登录");
    return false;
  }
}

/**
 * 检查用户类型
 */
function isUserType() {
  if (app.userInfo.carNum == null || app.userInfo.carNum == "") {
    return false;
  } else {
    return true;
  }
}